import Cookie from "js-cookie";

export function getTargetFromQuery(name = "") {
  let {
    location: { search }
  } = window;
  search = search.replace(/^\?/, "");
  const query = {};
  search.split("&").forEach(item => {
    let [key, value = ""] = item.split("=");
    query[key] = decodeURIComponent(value);
  });
  if (name) return query[name] || "";
  return query;
}

export function getAppid() {
  return getConfig("appid");
}

export function getRedirection() {
  return getConfig("target");
}

export function getConfig(key) {
  const query = getTargetFromQuery(key);
  const cookie = Cookie.get(key) || "";
  if ((!cookie && query) || (cookie && query && cookie !== query)) {
    Cookie.set(key, query);
  }
  if (!query && cookie) {
    return cookie;
  }
  return query;
}

export default {
  getTargetFromQuery,
  getAppid,
  getRedirection,
  getConfig
};
